//
//  LoopComposeView.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/15.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit
import pop

let composeBtnWidth:CGFloat = 80
let composeBtnHeight:CGFloat = 110
class LoopComposeView: UIView {

    lazy var btnArray:[LoopComposeButton] = [LoopComposeButton]()
    
    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){

        addSubview(bgImage)
        addSubview(titleView)
        
        addComposeBtn()
        
        setupCloseView()
        
        titleView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
    }
    
    
    //创建compose按钮的方法
    private func addComposeBtn(){
    
        let btnMargin = (screenWidth - composeBtnWidth * 3) / 4
        let composeBtn1:[String:Any] = ["title":"Text","image":#imageLiteral(resourceName: "tabbar_compose_idea")]
        let composeBtn2:[String:Any] = ["title":"Photo","image":#imageLiteral(resourceName: "tabbar_compose_photo")]
        let composeBtn3:[String:Any] = ["title":"Top Article","image":#imageLiteral(resourceName: "tabbar_compose_headlines")]
        let composeBtn4:[String:Any] = ["title":"Check in","image":#imageLiteral(resourceName: "tabbar_compose_lbs")]
        let composeBtn5:[String:Any] = ["title":"Live","image":#imageLiteral(resourceName: "tabbar_compose_weibo")]
        let composeBtn6:[String:Any] = ["title":"More","image":#imageLiteral(resourceName: "tabbar_compose_more")]

        var composeBtnArray:[[String:Any]] = [[String:Any]]()
        
        composeBtnArray.append(composeBtn1)
        composeBtnArray.append(composeBtn2)
        composeBtnArray.append(composeBtn3)
        composeBtnArray.append(composeBtn4)
        composeBtnArray.append(composeBtn5)
        composeBtnArray.append(composeBtn6)

        for (i,dic) in composeBtnArray.enumerated(){
            let btn = LoopComposeButton()
            let row = i / 3
            let col = i % 3
            let btnX = btnMargin + (composeBtnWidth + btnMargin) * CGFloat(col)
            let btnY = (composeBtnHeight + btnMargin) * CGFloat(row) + screenHeight
//            print(btnY)
            btn.frame = CGRect(x: btnX, y: btnY, width: composeBtnWidth, height: composeBtnHeight)
            btn.setTitle(dic["title"] as! String?, for: .normal)
            btn.setImage(dic["image"] as? UIImage, for: .normal)
            btn.addTarget(self, action: #selector(clickComposeBtn(btn:)), for: .touchUpInside)
            btnArray.append(btn)
            addSubview(btn)
        }
        
    }
    
    @objc private func clickComposeBtn(btn:LoopComposeButton){
        
        UIView.animate(withDuration: 0.25, animations: {
            for composeBtn in self.btnArray {
                if btn == composeBtn {
                    
                    composeBtn.transform = CGAffineTransform.init(scaleX: 2, y: 2)
                    composeBtn.alpha = 0
                }else{
                
                    composeBtn.transform = CGAffineTransform.init(scaleX: 0.2, y: 0.2)
                    composeBtn.alpha = 0
                }
                
            }
        }, completion: { (_) in
            
            let bundleName = Bundle.main.infoDictionary!["CFBundleName"] as! String
            let className = bundleName + "." + "LoopComposeViewController"
            guard let classType = NSClassFromString(className) as? UIViewController.Type else{
            return
            }
            let vc = classType.init()
            let nav = UINavigationController(rootViewController: vc)
            UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: {
                self.removeFromSuperview()
            })
        })
        
    }
    
    //按钮动画出现的效果
    func show(vc:UIViewController){
    
        vc.view.addSubview(self)
        for (index,btn) in btnArray.enumerated(){
            startBtnAnimation(btn: btn, isShow: true, index: index)
        }
    }
    
    private func startBtnAnimation(btn:LoopComposeButton,isShow:Bool,index:Int){
        
        //创建动画
        let btnAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        btnAnimation?.springSpeed = 10
        btnAnimation?.springBounciness = 5
        btnAnimation?.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        let btnCenterY = btn.center.y + CGFloat(isShow ? -350 : 350)
        btnAnimation?.toValue = NSValue.init(cgPoint: CGPoint(x: btn.center.x, y: btnCenterY))
        btn.pop_add(btnAnimation, forKey: "compose")
    }
    
    //底部关闭的按钮视图
    private func setupCloseView(){
        let closeView = UIView()
        addSubview(closeView)
        addSubview(closeBtn)
        
        closeView.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        
        closeBtn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_background_icon_close"), for: .normal)
        
        closeView.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(self)
            make.height.equalTo(40)
        }
        closeBtn.snp.makeConstraints { (make) in
            make.center.equalTo(closeView.snp.center)
        }
        
        closeBtn.addTarget(self, action: #selector(closeComposeView), for: .touchUpInside)
        
    }

    //关闭的动画
    @objc private func closeComposeView(){
        UIView.animate(withDuration: 0.25, animations: {
            
           self.closeBtn.transform = CGAffineTransform.init(rotationAngle: CGFloat(-M_PI_4))
            self.dismissCompose()
        })
    }
    
    private func dismissCompose(){
    
        for (index,btn) in btnArray.reversed().enumerated(){
            startBtnAnimation(btn: btn, isShow: false, index: index)
        }
        //延时执行视图移除
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.removeFromSuperview()
        }
    }
    
    //懒加载UI控件
    private lazy var closeBtn:UIButton = UIButton()
    
    private lazy var bgImage:UIImageView = UIImageView(image:UIImage.snapShotCurrentWindow().applyLightEffect())
    
    private lazy var titleView:UIImageView = UIImageView(image: #imageLiteral(resourceName: "compose_slogan"))
    
    //点击屏幕消失的方法
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        dismissCompose()
    }
    
}
